<template>
  <div class="mine-container">
    <Heads title="设置" :right-flag="false"></Heads>

    <van-cell-group class="mine-cell-item tl">
      <van-cell title="更换头像" center>
        <template #default>
          <van-uploader :disabled="disableFlag" :before-read="beforeRead" :after-read="afterReadAvatar">
            <van-image
              round
              width="32"
              height="32"
              fit="cover"
              :src="userinfo.avatar ? userinfo.avatar : require('@/assets/missing-face.png')"
            />
          </van-uploader>
        </template>
      </van-cell>
    </van-cell-group>

    <van-cell-group class="mine-cell-item tl">
      <van-cell title="更换背景" center>
        <van-uploader :disabled="disableFlag" :before-read="beforeRead" :after-read="afterReadPoster">
          <template #default>
            <van-image
              round
              width="32"
              height="32"
              :src="userinfo.poster ? userinfo.poster : require('@/assets/user-bg.png')"
            />
          </template>
        </van-uploader>
      </van-cell>
    </van-cell-group>

    <van-cell-group class="mine-cell-item tl">
      <van-cell title="修改密码" is-link @click="toModifyPwd"></van-cell>
    </van-cell-group>

    <van-cell-group class="mine-cell-item tl">
      <van-cell title="关于我们"></van-cell>
      <van-cell title="检查更新"></van-cell>
      <van-cell title="当前版本 1.0.0"></van-cell>
    </van-cell-group>

    <van-cell-group class="mine-cell-item">
      <van-cell title="切换账号" :to="{name: 'User-type',params: { type: 'login' }}"></van-cell>
      <van-cell title="退出登录" @click="quitLogin"></van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { post, postFile } from "@/utils/axios";
import { mapState, mapMutations, mapActions } from "vuex";
import Vue from "vue";
import { Uploader, Image as VanImage, Cell, CellGroup, Toast } from "vant";

Vue.use(Uploader)
  .use(VanImage)
  .use(Cell)
  .use(CellGroup)
  .use(Toast);
export default {
  data() {
    return {};
  },
  computed: {
    ...mapState("userModule", ["userinfo", "token"]),
    disableFlag() {
      if(this.token) {
        return false
      } else {
        return true
      }
    }
  },
  methods: {
    ...mapMutations("footerModule", ["FOOTERSHOW"]),
    ...mapMutations("userModule", ["CHANGETOKEN", "CHANGEUSERINFO"]),
    ...mapActions("userModule", ["GETUSERINFO"]),
    quitLogin() {
      if (!this.token) {
        Toast({
          message: "您好，先去登录吧！",
          closeOnClick: true,
          forbidClick: true,
          duration: 500
        });
        return
      }
      post({
        url: "/hybrid/users/quit"
      }).then(res => {
        if (res.status === 0) {
          Toast({
            message: "退出成功",
            closeOnClick: true,
            forbidClick: true,
            duration: 500
          });
          this.CHANGETOKEN("");
          this.CHANGEUSERINFO({});
          this.$router.replace({
            name: "Home"
          });
        }
      });
    },
    /********************* -------- *********************/
    /********************* 上传start *********************/
    /********************* -------- *********************/
    /**
     * 通过传入beforeRead函数可以在上传前进行校验
     * 方式一: 返回true表示校验通过，返回false表示校验失败。
     * 方拾贰: 支持返回Promise对 file 对象进行自定义处理，例如压缩图片。
     *   multiple
        :max-count="5"
        :max-size="3 * 1024 * 1024"
        @oversize="onOversize"
     */
    // 返回布尔值
    beforeRead(file) {
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJpgOrPng) {
        Toast({
          message: "请上传 jpeg | jpg | png 格式图片",
          closeOnClick: true,
          forbidClick: true,
          duration: 500
        });
        return false;
      }
      if (!isLt2M) {
        Toast({
          message: "大小不能超过 2MB!",
          closeOnClick: true,
          forbidClick: true,
          duration: 500
        });
        return false;
      }
      return isJpgOrPng && isLt2M;
    },
    /** 返回 Promise
    asyncBeforeRead(file) {
      return new Promise((resolve, reject) => {
        if (file.type !== "image/jpeg") {
          this.$toast("请上传 jpg 格式图片");
          reject();
        } else {
          let img = new File(["foo"], "bar.jpg", {
            type: "image/jpeg"
          });
          resolve(img);
        }
      });
    },*/
    afterReadAvatar(file) {
      // 此时可以自行将文件上传至服务器(NOTE: 此处vant传递的参数的file属性才是需要上传的文件类型)
      // console.log(typeof(file), typeof(file.file));
      // if (!file.file) return
      let form = new FormData();
      form.append("file", file.file);
      postFile({
        url: `/hybrid/uni/upload-avatar`,
        data: form
      }).then(res => {
        this.GETUSERINFO();
      });
    },
    afterReadPoster(file) {
      let form = new FormData();
      form.append("file", file.file);
      postFile({
        url: `/hybrid/uni/upload-bg`,
        data: form
      }).then(res => {
        this.GETUSERINFO();
      });
    },
    /********************* ------- *********************/
    /********************* 上传end *********************/
    /********************* ------- *********************/
    toModifyPwd() {
      if (!this.token) {
        Toast({
          message: "您好，先去登录吧！",
          closeOnClick: true,
          forbidClick: true,
          duration: 500
        });
        return
      } else {
        this.$router.push({
          name: 'User-modify-pwd'
        })
      }
    }
  },
  mounted() {
    this.FOOTERSHOW(false);
  },
  destroyed() {
    this.FOOTERSHOW(true);
  }
};
</script>

<style lang="scss" scoped>
.mine-container {
  .mine-cell-item {
    margin: 24px 14px;
    border-radius: 10px;
    overflow: hidden;
    &.tl {
      text-align: left;
    }
  }
}
</style>
